package com.wudi.estate.controller.homemanage;

import com.wudi.estate.bean.communitymanagement.Community;
import com.wudi.estate.bean.homemanage.Buildings;
import com.wudi.estate.mapper.communitymanagement.CommunityMapper;
import com.wudi.estate.service.communitymanagement.CommunityService;
import com.wudi.estate.service.homemanage.BuildingsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import java.util.*;

@SessionAttributes(value = "community1")
@RequestMapping("/buildings")
@Controller
public class BuildingsController {
    @Autowired
    private BuildingsService buildingsService;
    @Autowired
    private CommunityService communityService;
    @RequestMapping("/listUi")
    public String buildings_list(ModelMap map) throws Exception {
        List<Community> community1 = communityService.select();
        map.addAttribute("community1",community1);
        List<Map<String,Object>> buildingAndCommunity = new ArrayList<>();
        List<Buildings> buildingsList = buildingsService.selectAll();
        for (Buildings b:buildingsList) {
            Map<String,Object> m =new HashMap<>();
            Community community = communityService.selectById(b.getCid());
            m.put("buildings",b);
            m.put("community",community);
            buildingAndCommunity.add(m);
        }
        map.addAttribute("buildingAndCommunity",buildingAndCommunity);
        return "building_list";
    }
    @RequestMapping("/addUi")
    public String building_addUi(){
        return "building_add";
    }
    @RequestMapping("/add")
    public String building_add(Buildings buildings){
        buildings.setCreateTime(new Date());
        try {
            buildingsService.insert(buildings);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "redirect:/buildings/listUi";
    }
    @RequestMapping("/editUi")
    public String building_editUi(long id ,ModelMap map){
        Buildings b =new Buildings();
        b.setId(id);
        Buildings buildings =new Buildings();
        try {
            buildings = buildingsService.selectById(b);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        map.addAttribute("buildings",buildings);
        return "building_edit";
    }
    @RequestMapping("/edit")
    public String building_edit(Buildings buildings){
        buildings.setCreateTime(new Date());
        try {
            buildingsService.upadteById(buildings);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "redirect:/buildings/listUi";
    }
}
